#include "words.h"
#include "defs.h"


char** ReadWordsFromFiles(char** words, int* nWords, char** filesNames, int nFiles)
{
	int i = 0;

	*nWords = 0;

	for(i = 0; i < nFiles ; ++i)
	{
		FILE* file = fopen(filesNames[i],"r");

		if (!file)
			{
				fprintf(stderr,"Error al abrir el archivo %s",filesNames[i]);
				return words;
			}

		words = ReadWordsFromFile(words, nWords, file);

		if (file)
			fclose(file);
	}

	return words;
}

char** ReadWordsFromFile(char** words, int* nWords, FILE* file)
{
	if (!file)
		return words;

	char* buffer = NULL;

	fseek (file, 0, SEEK_END);
	int sizeBuffer = ftell(file);

	// archivo empty
	if (sizeBuffer<0)
		return words;

	buffer = (char*)calloc(sizeBuffer+1,sizeof(char));
	fseek(file, 0L, SEEK_SET);
	fread(buffer,sizeof(char), sizeBuffer, file);

	if (ferror(file))
	{
		fprintf(stderr,"Error en lectura del archivo de entrada");
		return words;
	}

	char * pch;
	pch = strtok(buffer," ");

	while (pch != NULL)
	{
		(*nWords)++;

		words = (char**)realloc(words, (*nWords)*sizeof(char*));

		words[(*nWords) - 1] = (char*)malloc((strlen(pch)+1)*sizeof(char));
		strcpy(words[(*nWords) - 1], pch);

		pch = strtok(NULL, " \t\n\v\f\r");
	}

	if (buffer)
		free(buffer);


	return words;
}

int FreeWords(char** words, int nWords)
{
	int error = 0;

	int i = 0;
	for(i = 0; i < nWords; ++i)
	{
		free(words[i]);
	}

	free(words);

	return error;
}

void PrintWords(char** words, int nWords)
{
	int i = 0;

	for(i = 0; i < nWords; i++)
	{
		printf("%s ",words[i]);
	}

}
